<?php
class loginAction extends sfAction
{

  public function execute($request)
  {
    if (sfConfig::get('app_anonymous_login'))
    {
      $this->getUser()->setAuthenticated(true);
    }
    if ($this->getUser()->isAuthenticated())
    {
      $this->forward('log', 'list');
    }
    $this->form = new connexionForm();
    if ($this->getRequest()->isMethod(sfRequest::POST))
    {
      $this->form->bind($request->getParameter('connexion'));
      $user   = $this->form->getValue('user');
      $pass   = $this->form->getValue('pass');
      $server = sfConfig::get('app_ldap_server');

      $ad_base_search = sfConfig::get('app_ldap_search');
      $ds=ldap_connect($server);

      ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
      ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);

      $r      = ldap_bind($ds, sfConfig::get('app_ldap_username'), sfConfig::get('app_ldap_password'));
      $filter = sprintf('(%s=%s)', sfConfig::get('app_ldap_attr_username'), trim($user));
      $sr     = ldap_search($ds, $ad_base_search, $filter);
      $infos  = ldap_get_entries($ds, $sr);
      ldap_unbind($ds);

      if ($infos['count']  === 1)
      {
        $ds2 = ldap_connect($server);
        ldap_set_option($ds2, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ds2, LDAP_OPT_REFERRALS, 0);
        if ($rs = ldap_bind($ds2, $user, $pass))
        {
          $nom = $infos[0][sfConfig::get('app_ldap_attr_displayedname')][0];
          $this->getUser()->setAuthenticated(true);
          $this->getUser()->setAttribute('nom', $nom);
          $this->redirect('@homepage');
        }
        ldap_close($ds2);
      }
    }
  }

}